package com.rat.datadictionary.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.rat.datadictionary.config.DynamicDataSource;
import com.rat.datadictionary.entity.DataDictionary;
import com.rat.datadictionary.service.DataDictionaryService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @description:
 * @author: Howe
 * @create: 2021-01-07 11:34
 */
@RestController
@RequestMapping("data")
public class DataDictionaryController {
    @Resource
    private DataDictionaryService dataDictionaryService;


    /**
     * @Description: 根据数据库和表名查询数据字典字段
     * @Param:
     * @Return:
     * @Author: Howe
     * @Date: 2021/1/7 14:12
     **/
    @PostMapping("dictionary")
    public List<List<DataDictionary>> findDataDictionary(@RequestBody DataDictionary dataDictionary) {
        return dataDictionaryService.findDataDictionary(dataDictionary);
    }

    /**
     * @Description: 根据数据库连接，导出数据结构excel
     * @Param:
     * @Return:
     * @Author: Howe
     * @Date: 2021/1/7 17:42
     **/
    @PostMapping("down")
    public void downLoadDataDictionaryExcel(@RequestBody DataDictionary dataDictionary, HttpServletResponse response) throws Exception {
        if (dataDictionary.getDatabaseConnection() != null) {
            DruidDataSource druidDataSource = new DruidDataSource();
            //数据库地址
            druidDataSource.setUrl(dataDictionary.getDatabaseConnection().getUrl());
            //账号
            druidDataSource.setUsername(dataDictionary.getDatabaseConnection().getUsername());
            //密码
            druidDataSource.setPassword(dataDictionary.getDatabaseConnection().getPassword());
            DynamicDataSource.dataSourcesMap.put(String.valueOf(System.currentTimeMillis()), druidDataSource);
            DynamicDataSource.setDataSource(String.valueOf(System.currentTimeMillis()));
        }

        dataDictionaryService.downLoadDataDictionaryExcel(response, dataDictionary);
    }


}
